<?php

class OrderController extends Controller
{
    public $_model;

    public function filters()
    {
        return array(
            'accessControl',
        );
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array('view', 'create', 'confirm', 'success', 'failure', 'payment', 'finalize'),
                'users' => array('*'),
            ),
            array('allow',
                'actions' => array('admin', 'delete', 'view', 'slip', 'invoice'),
                'users' => array('admin'),
            ),
            array('deny', // deny all other users
                'users' => array('*'),
            ),
        );
    }

    public function actionSlip($id)
    {
        if ($model = $this->loadModel($id))
            $this->render(Shop::module()->slipView, array('model' => $model));
    }

    public function loadModel()
    {
        if ($this->_model === null) {
            if (isset($_GET['id']))
                $this->_model = Order::model()->findbyPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }

    public function actionInvoice($id)
    {
        if ($model = $this->loadModel($id))
            $this->render(Shop::module()->invoiceView, array('model' => $model));
    }

    public function beforeAction($action)
    {
        $products = Shop::getCartContent();
        if(!$products && (Yii::app()->controller->action->id != 'success' && Yii::app()->controller->action->id != 'failure')){
            $this->redirect('/shop/shoppingCart/view');
        }
        $this->layout = Shop::module()->layout;
        return parent::beforeAction($action);
    }

    public function actionView()
    {
        $this->render('view', array(
            'model' => $this->loadModel(),
        ));
    }

    /** Creation of a new Order
     * Before we create a new order, we need to gather Customer information.
     * If the user is logged in, we check if we already have customer information.
     * If so, we go directly to the Order confirmation page with the data passed
     * over. Otherwise we need the user to enter his data, and depending on
     * whether he is logged in into the system it is saved with his user
     * account or once just for this order.
     */
    public function actionCreate($customer = null)
    {
        Yii::app()->user->setState('payment_method', Order::PAYMENT_PAYPAL);

        $criteria = new CDbCriteria();
        $criteria->order = 'name asc';
        $countryList = Country::model()->findAll($criteria);
 
        if (!$customer)
            $customer = Yii::app()->user->getState('customer_id');
        if (!Yii::app()->user->isGuest && !$customer)
            $customer = Customer::model()->find('user_id = :user_id ', array(
                ':user_id' => Yii::app()->user->id));

        if (!$customer) {
            $this->render('/customer/create', array(
                'action' => array('//shop/customer/create'),
            	'countryList' => $countryList
            ));
            Yii::app()->end();
        } else {
            //$this->redirect(array('/shop/order/confirm'));
            $model = Shop::getCustomer();
            $deliveryAddress = $model->deliveryAddress;
            $billingAddress = $model->billingAddress;

            //$this->render('/customer/update', array(
            $this->render('/customer/account-info', array(
                'customer' => $model,
                'deliveryAddress' => $deliveryAddress,
                'billingAddress' => $billingAddress,
                'action' => array('//shop/customer/update'),
            	'countryList' => $countryList
            ));
            Yii::app()->end();
        }
    }

    public function actionConfirm($customer = null)
    {
        if (!$customer)
            $customer = Yii::app()->user->getState('customer_id');

        if (!$customer) {
            $this->render('/customer/create', array(
                'action' => array('//shop/customer/create')));
            Yii::app()->end();
        }
     
        $cart = Shop::getCartContent();
        $this->render('/order/confirm', array(
            'action' => array('//shop/order/process-payment'),
            'products' => $cart,
        ));

    }

    public function actionFinalize()
    {
        $PayPalMode = Yii::app()->params['PayPalMode'];
        $PayPalApiUsername = Yii::app()->params['PayPalApiUsername'];
        $PayPalApiPassword = Yii::app()->params['PayPalApiPassword'];
        $PayPalApiSignature = Yii::app()->params['PayPalApiSignature'];
        $PayPalCurrencyCode = Yii::app()->params['PayPalCurrencyCode'];

        //Paypal redirects back to this page using ReturnURL, We should receive TOKEN and Payer ID
        if (isset($_GET["token"]) && isset($_GET["PayerID"])) {
            //we will be using these two variables to execute the "DoExpressCheckoutPayment"
            //Note: we haven't received any payment yet.

            $token = $_GET["token"];
            $payer_id = $_GET["PayerID"];

            //get session variables
            $paypal_product = $_SESSION["paypal_products"];
            $paypal_data = '';
            $ItemTotalPrice = 0;

            foreach ($paypal_product['items'] as $key => $p_item) {
                $paypal_data .= '&L_PAYMENTREQUEST_0_QTY' . $key . '=' . urlencode($p_item['itm_qty']);
                $paypal_data .= '&L_PAYMENTREQUEST_0_AMT' . $key . '=' . urlencode($p_item['itm_price']);
                $paypal_data .= '&L_PAYMENTREQUEST_0_NAME' . $key . '=' . urlencode($p_item['itm_name']);
                $paypal_data .= '&L_PAYMENTREQUEST_0_NUMBER' . $key . '=' . urlencode($p_item['itm_code']);

                // item price X quantity
                $subtotal = ($p_item['itm_price'] * $p_item['itm_qty']);

                //total price
                $ItemTotalPrice = ($ItemTotalPrice + $subtotal);
            }

            $padata = '&TOKEN=' . urlencode($token) .
                '&PAYERID=' . urlencode($payer_id) .
                '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") .
                $paypal_data .
                '&PAYMENTREQUEST_0_ITEMAMT=' . urlencode($ItemTotalPrice) .
                '&PAYMENTREQUEST_0_TAXAMT=' . urlencode($paypal_product['assets']['tax_total']) .
                '&PAYMENTREQUEST_0_SHIPPINGAMT=' . urlencode($paypal_product['assets']['shippin_cost']) .
                '&PAYMENTREQUEST_0_HANDLINGAMT=' . urlencode($paypal_product['assets']['handaling_cost']) .
                '&PAYMENTREQUEST_0_SHIPDISCAMT=' . urlencode($paypal_product['assets']['shippin_discount']) .
                '&PAYMENTREQUEST_0_INSURANCEAMT=' . urlencode($paypal_product['assets']['insurance_cost']) .
                '&PAYMENTREQUEST_0_AMT=' . urlencode($paypal_product['assets']['grand_total']) .
                '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($PayPalCurrencyCode);

            //We need to execute the "DoExpressCheckoutPayment" at this point to Receive payment from user.
            $paypal = new MyPayPal();
            $httpParsedResponseAr = $paypal->PPHttpPost('DoExpressCheckoutPayment', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);

            //Check if everything went ok..
            if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {

                echo '<h2>Success</h2>';
                $transactionId = urldecode($httpParsedResponseAr["PAYMENTINFO_0_TRANSACTIONID"]);
                echo 'Your Transaction ID : ' . $transactionId;

                /*
                //Sometimes Payment are kept pending even when transaction is complete.
                //hence we need to notify user about it and ask him manually approve the transiction
                */

                if ('Completed' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
                    echo '<div style="color:green">Payment Received! Your product will be sent to you very soon!</div>';
                } elseif ('Pending' == $httpParsedResponseAr["PAYMENTINFO_0_PAYMENTSTATUS"]) {
                    echo '<div style="color:red">Transaction Complete, but payment is still pending! ' .
                        'You need to manually authorize this payment in your <a target="_new" href="http://www.paypal.com">Paypal Account</a></div>';
                }

                // we can retrive transection details using either GetTransactionDetails or GetExpressCheckoutDetails
                // GetTransactionDetails requires a Transaction ID, and GetExpressCheckoutDetails requires Token returned by SetExpressCheckOut
                $padata = '&TOKEN=' . urlencode($token);
                $paypal = new MyPayPal();
                $httpParsedResponseAr = $paypal->PPHttpPost('GetExpressCheckoutDetails', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);

                if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
                    // Save data to database =======================================================================================
                    $order = new Order();
                    $customer = Shop::getCustomer();

                    $cart = Shop::getCartContent();
                    $order->customer_id = $customer->customer_id;
                    $order->delivery_address_id = $customer->delivery_address_id;
                    $order->billing_address_id = $customer->billing_address_id;
                    $order->ordering_date = date('Y-m-d H:i:s');
                    $order->payment_method = 5;//Yii::app()->user->getState('payment_method');
                    $order->transaction_id = $transactionId;
                    $order->comment = Yii::app()->user->getState('order_comment');

                    if ($order->save()) {
                        foreach ($cart as $position => $product) {
                            $position = new OrderPosition;
                            $position->order_id = $order->order_id;
                            $position->product_id = $product['product_id'];
                            $position->amount = $product['amount'];
                            $position->specifications = @json_encode($product['Variations']);
                            $position->save();
                            Yii::app()->user->setState('cart', array());
                            Yii::app()->user->setState('order_comment', null);
                        }
                        Shop::mailNotification($order);
                        $this->redirect(Shop::module()->successAction);
                    } else
                        $this->redirect(Shop::module()->failureAction);
                } else {
                    echo '<div style="color:red"><b>GetTransactionDetails failed:</b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
                    echo '<pre>';
                    print_r($httpParsedResponseAr);
                    echo '</pre>';
                }

            } else {
                echo '<div style="color:red"><b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
                echo '<pre>';
                print_r($httpParsedResponseAr);
                echo '</pre>';
            }
        }

        $this->redirect(array('//shop/order/confirm'));
    }

    public function actionSuccess()
    {
        $this->render('/order/success');
    }

    public function actionFailure()
    {
        $this->render('/order/failure');
    }

    public function actionAdmin()
    {
        $model = new Order('search');
        if (isset($_GET['Order']))
            $model->attributes = $_GET['Order'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    public function actionPayment()
    {
        $PayPalMode = Yii::app()->params['PayPalMode'];
        $PayPalApiUsername = Yii::app()->params['PayPalApiUsername'];
        $PayPalApiPassword = Yii::app()->params['PayPalApiPassword'];
        $PayPalApiSignature = Yii::app()->params['PayPalApiSignature'];
        $PayPalCurrencyCode = Yii::app()->params['PayPalCurrencyCode'];
        $PayPalReturnURL = Yii::app()->params['PayPalReturnURL'];
        $PayPalCancelURL = Yii::app()->params['PayPalCancelURL'];

        //Other important variables like tax, shipping cost
        $TotalTaxAmount = Yii::app()->params['TotalTaxAmount'];
        $HandalingCost = Yii::app()->params['HandalingCost'];
        $InsuranceCost = Yii::app()->params['InsuranceCost'];
        $ShippinDiscount = Yii::app()->params['ShippinDiscount'];
        //$ShippinCost = Yii::app()->params['ShippinCost'];
		$ShippinCost = Shop::priceFormat(Shop::getShippingTotal());
        //Parameters for SetExpressCheckout, which will be sent to PayPal

        $products = Shop::getCartContent();
        $padata = '';
        if ($products) {
            $i = 0;
            $padata = '&METHOD=SetExpressCheckout' .
                '&RETURNURL=' . urlencode($PayPalReturnURL) .
                '&CANCELURL=' . urlencode($PayPalCancelURL) .
                '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE");
            foreach ($products as $pos => $product) {
                if (@$model = Products::model()->findByPk($product['product_id'])) {
                    $variations = '';
                    if (isset($product['frame-included'])) {
                        // Check frame included
                        $variations = 1;
                    }
                    $padata .= '&L_PAYMENTREQUEST_0_NAME' . $i . '=' . urlencode($model['title']);
                    $padata .= '&L_PAYMENTREQUEST_0_NUMBER' . $i . '=' . urlencode($product['product_id']);
                    $padata .= '&L_PAYMENTREQUEST_0_AMT' . $i . '=' . urlencode(Shop::priceFormat($model->getPrice(@$variations)));
                    $padata .= '&L_PAYMENTREQUEST_0_QTY' . $i . '=' . urlencode($product['amount']);
                }
                $i++;
                //create items for session
                $paypal_product['items'][] = array(
                    'itm_name' => $model['title'],
                    'itm_price' => Shop::priceFormat($model->getPrice(@$variations)),
                    'itm_code' => $product['product_id'],
                    'itm_qty' => $product['amount']
                );
            }
            $padata .= '&NOSHIPPING=1'; //set 1 to hide buyer's shipping address, in-case products that does not require shipping
        }

        //Grand total including all tax, insurance, shipping cost and discount
        $GrandTotal = (Shop::getPriceTotal() + $TotalTaxAmount + $HandalingCost + $InsuranceCost + $ShippinCost + $ShippinDiscount);

        $paypal_product['assets'] = array('tax_total' => $TotalTaxAmount,
            'handaling_cost' => $HandalingCost,
            'insurance_cost' => $InsuranceCost,
            'shippin_discount' => $ShippinDiscount,
            'shippin_cost' => $ShippinCost,
            'grand_total' => $GrandTotal);

        //create session array for later use
        $_SESSION["paypal_products"] = $paypal_product;

        //Parameters for SetExpressCheckout, which will be sent to PayPal
        $padata = '&METHOD=SetExpressCheckout' .
            '&RETURNURL=' . urlencode($PayPalReturnURL) .
            '&CANCELURL=' . urlencode($PayPalCancelURL) .
            '&PAYMENTREQUEST_0_PAYMENTACTION=' . urlencode("SALE") .
            $padata .
            '&NOSHIPPING=0' . //set 1 to hide buyer's shipping address, in-case products that does not require shipping
            '&PAYMENTREQUEST_0_ITEMAMT=' . urlencode(Shop::getPriceTotal()) .
            '&PAYMENTREQUEST_0_TAXAMT=' . urlencode($TotalTaxAmount) .
            '&PAYMENTREQUEST_0_SHIPPINGAMT=' . urlencode($ShippinCost) .
            '&PAYMENTREQUEST_0_HANDLINGAMT=' . urlencode($HandalingCost) .
            '&PAYMENTREQUEST_0_SHIPDISCAMT=' . urlencode($ShippinDiscount) .
            '&PAYMENTREQUEST_0_INSURANCEAMT=' . urlencode($InsuranceCost) .
            '&PAYMENTREQUEST_0_AMT=' . urlencode($GrandTotal) .
            '&PAYMENTREQUEST_0_CURRENCYCODE=' . urlencode($PayPalCurrencyCode) .
            '&LOCALECODE=GB' . //PayPal pages to match the language on your website.
            '&LOGOIMG=http://petitpoint.com.vn/data/images/pp-logo.png' . //site logo
            '&CARTBORDERCOLOR=FFFFFF' . //border color of cart
            '&ALLOWNOTE=1';


        $paypalmode = ($PayPalMode == 'sandbox') ? '.sandbox' : '';

        $paypal = new MyPayPal();
        $httpParsedResponseAr = $paypal->PPHttpPost('SetExpressCheckout', $padata, $PayPalApiUsername, $PayPalApiPassword, $PayPalApiSignature, $PayPalMode);

        //Respond according to message we receive from Paypal
        if ("SUCCESS" == strtoupper($httpParsedResponseAr["ACK"]) || "SUCCESSWITHWARNING" == strtoupper($httpParsedResponseAr["ACK"])) {
            //Redirect user to PayPal store with Token received.
            $paypalurl = 'https://www' . $paypalmode . '.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=' . $httpParsedResponseAr["TOKEN"] . '';
            header('Location: ' . $paypalurl);
        } else {
            //Show error message
            echo '<div style="color:red"><b>Error : </b>' . urldecode($httpParsedResponseAr["L_LONGMESSAGE0"]) . '</div>';
            echo '<pre>';
            print_r($httpParsedResponseAr);
            echo '</pre>';
        }
    }


}
